//游戏主文件
import Json from "../../json/json.js"
import Global from "store"
cc.Class({
    extends: cc.Component,

    properties: {
        P_blockWidth: {
            default: 106,
            tooltip: "每个地图块的宽度",
        },
        P_blockHeight: {
            default: 106,
            tooltip: "每个地图块的高度",
        },
        P_monsterSpeed: {
            default: 0.5,
            tooltip: "怪物移动的速度"
        },
        P_blockAtllas: {
            default: null,
            type: cc.SpriteAtlas,
            tooltip: "地图块的图集"
        }
    },

    // LIFE-CYCLE CALLBACKS:
    ctor() {
        let json = JSON.parse(JSON.stringify(Json))
        Global.mapData = json.mapData;
        Global.pathData = json.pathData;
        Global.cannonData = json.cannonList;
        Global.pathSizeData = [];
        for (let i = 0; i < Global.pathData.length; i++) {
            //路径坐标转换成点坐标
            let xWidth = Global.pathData[i][0] * this.P_blockWidth + this.P_blockWidth / 2;
            let yHgieht = -Global.pathData[i][1] * this.P_blockHeight - this.P_blockHeight / 2;
            Global.pathSizeData.push(cc.v2(xWidth, yHgieht))
        }
    },
    onLoad() {
        this.creatGameMap(Global.pathData)
        Global.main = this;
    },

    creatGameMap() {
        //生成游戏地图
        let xBlockNumber = parseInt(this.node.width / this.P_blockWidth); //x轴块的数量
        let yBlockNumber = parseInt(this.node.height / this.P_blockHeight); //Y轴块的数量
        for (let i = 0; i < yBlockNumber; i++) {
            let y = this.P_blockHeight * i; //y轴坐标
            for (let o = 0; o < xBlockNumber; o++) {
                let x = this.P_blockWidth * o; //x轴坐标
                let posx = x + this.P_blockWidth / 2 //因为每一个块的锚点在中心(0.5,0.5) 所以哑巴他的中信移到(0,1)
                let posy = -y - this.P_blockHeight / 2 //每一个块的坐标点 -y 是因为mapView 的锚点在(0,1) 向下y就要是负
                let pos = cc.v2(posx, posy);
                let spriteFrame = Global.mapData[i][o]
                this.creatBlock(pos, spriteFrame);
            }
        }
    },
    creatBlock(pos, spriteFrame) {
        //生成块
        let block = new cc.Node; //创建一个节点
        this.node.addChild(block); //把创建的节点添加在mapView节点上
        let component = block.addComponent(cc.Sprite); //在创建的节点上添加Sprite组件
        var frame = this.P_blockAtllas.getSpriteFrame(spriteFrame); //获取地图块的图集的一张图片
        component.spriteFrame = frame; //块组件的照片赋值
        block.setPosition(pos); //设置块的位置
    }
});